using System;
using System.IO;
using System.Collections;

namespace Patchy
{
	/// <summary>
	/// Summary description for BatchUninstall.
	/// </summary>
	public class BatchUninstall
	{
        GroupHolder mGroupHolder;
		PatchDetails mDetails;

        public BatchUninstall(PatchDetails mDetails, GroupHolder groupHolder)
		{
            mGroupHolder = groupHolder;
			this.mDetails = mDetails;
		}
		
		public new string ToString()
		{
            string patchname, backupdir, makebackupdir, copyback;

            patchname = string.Format("{0}", mDetails.PatchBaseFileName);
            backupdir = @"C:\Backup\%PATCHNAME%\";
			makebackupdir = "";
            foreach (string alias in mGroupHolder.AliasTable.Keys)
            {
                makebackupdir += string.Format("SET {0}={1}\r\n", alias, mGroupHolder.AliasTable[alias].ToString());
            }
            copyback = "";
            foreach (MyGroup group in mGroupHolder.SortedGroupCollection)
			{
                foreach (MyFile file in group.Files)
				{
                    copyback += string.Format("IF EXIST \"%BACKUPDIR%{0}\" (\r\n\tECHO {0}\r\n", file.ShortenedName);
                    copyback += string.Format("\tCOPY \"%BACKUPDIR%{0}\" \"{1}{2}\" /y\r\n)\r\n",
                        file.ShortenedName,
                        group.AliasCombined,
                        file.FileNamePart);
				}
			}

            string[] formatArgs = { patchname, backupdir, makebackupdir, copyback };
			return string.Format(text, formatArgs);
		}
		
		private string text = @"@ECHO OFF
CLS

SET PATCHNAME={0}

SET BACKUPDIR={1}

{2}
iisreset /STOP

@ECHO Waiting 3 seconds
PING 1.1.1.1 -n 1 -w 3000 >NUL

@ECHO off
@ECHO ------------------------------------------
@ECHO Copy files back
@ECHO ------------------------------------------

{3}
@ECHO ------------------------------------------
@ECHO Start Up Service(s) 
@ECHO ------------------------------------------

iisreset /START

@ECHO ON
@ECHO ------------------------------------------
@ECHO DONE!
@ECHO ------------------------------------------

@PAUSE
";
	}
}
